<template>
  <div class="error-test-page">
    <div class="container-box">
      <el-card class="error-test-card">
        <template #header>
          <h2>全局错误处理测试页面</h2>
          <p class="subtitle">测试各种类型的错误和全局错误处理功能</p>
        </template>

        <div class="test-sections">
          <!-- JavaScript 错误测试 -->
          <section class="test-section">
            <h3>JavaScript 错误测试</h3>
            <div class="button-group">
              <el-button @click="triggerJSError" type="danger" size="default">
                <el-icon><Warning /></el-icon>
                触发 JS 错误
              </el-button>
              <el-button @click="triggerTypeError" type="danger" size="default">
                <el-icon><Warning /></el-icon>
                触发类型错误
              </el-button>
              <el-button @click="triggerReferenceError" type="danger" size="default">
                <el-icon><Warning /></el-icon>
                触发引用错误
              </el-button>
            </div>
          </section>

          <!-- Vue 组件错误测试 -->
          <section class="test-section">
            <h3>Vue 组件错误测试</h3>
            <div class="button-group">
              <el-button @click="triggerRenderError" type="warning" size="default">
                <el-icon><Warning /></el-icon>
                触发渲染错误
              </el-button>
              <el-button @click="triggerLifecycleError" type="warning" size="default">
                <el-icon><Warning /></el-icon>
                触发生命周期错误
              </el-button>
              <el-button @click="triggerWatchError" type="warning" size="default">
                <el-icon><Warning /></el-icon>
                触发 Watch 错误
              </el-button>
            </div>
          </section>

          <!-- Promise 错误测试 -->
          <section class="test-section">
            <h3>Promise 错误测试</h3>
            <div class="button-group">
              <el-button @click="triggerPromiseError" type="primary" size="default">
                <el-icon><Warning /></el-icon>
                触发 Promise 拒绝
              </el-button>
              <el-button @click="triggerAsyncError" type="primary" size="default">
                <el-icon><Warning /></el-icon>
                触发 Async/Await 错误
              </el-button>
            </div>
          </section>

          <!-- 网络错误测试 -->
          <section class="test-section">
            <h3>网络错误测试</h3>
            <div class="button-group">
              <el-button @click="triggerNetworkError" type="info" size="default">
                <el-icon><Warning /></el-icon>
                模拟网络请求错误
              </el-button>
              <el-button @click="triggerResourceError" type="info" size="default">
                <el-icon><Warning /></el-icon>
                模拟资源加载错误
              </el-button>
            </div>
          </section>

          <!-- 错误管理功能测试 -->
          <section class="test-section">
            <h3>错误管理功能</h3>
            <div class="button-group">
              <el-button @click="showErrorQueue" type="success" size="default">
                <el-icon><List /></el-icon>
                查看错误队列 ({{ errorQueue.length }})
              </el-button>
              <el-button @click="clearErrors" type="success" size="default">
                <el-icon><Delete /></el-icon>
                清空错误队列
              </el-button>
              <el-button @click="checkHandlerHealth" type="info" size="default">
                <el-icon><Monitor /></el-icon>
                检查处理器状态
              </el-button>
            </div>
          </section>

          <!-- 调试工具测试 -->
          <section class="test-section">
            <h3>调试工具</h3>
            <div class="button-group">
              <el-button @click="testErrorBall" type="primary" size="default">
                <el-icon><Cpu /></el-icon>
                测试错误球响应
              </el-button>
              <el-button @click="simulateErrorHandlerFailure" type="danger" size="default">
                <el-icon><Warning /></el-icon>
                模拟处理器异常
              </el-button>
            </div>
          </section>
        </div>

        <!-- 错误队列显示 -->
        <el-collapse v-if="showQueue" class="error-queue">
          <el-collapse-item title="错误队列详情" name="queue">
            <div v-if="errorQueue.length === 0" class="empty-queue"> 暂无错误记录 </div>
            <div v-else>
              <div v-for="(error, index) in errorQueue" :key="index" class="error-item">
                <div class="error-header">
                  <span class="error-type">{{ error.type }}</span>
                  <span class="error-time">{{ formatTime(error.timestamp) }}</span>
                </div>
                <div class="error-message">{{ error.message }}</div>
                <div v-if="error.stack" class="error-stack">
                  <pre>{{ error.stack.slice(0, 200) }}...</pre>
                </div>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>

        <!-- 使用说明 -->
        <el-alert class="usage-info" title="使用说明" type="info" :closable="false">
          <template #default>
            <ul>
              <li><strong>开发环境</strong>：错误发生后会在右下角显示可拖动的红色错误球</li>
              <li><strong>生产环境</strong>：错误发生后会显示全局错误弹窗</li>
              <li>点击错误球可以查看错误记录列表，点击列表项查看详情</li>
              <li>错误球显示错误总数，超过99个显示99+</li>
              <li>错误球可以拖动到任意位置，松手后自动吸边</li>
              <li>可以在错误详情中快速搜索解决方案或复制错误信息</li>
              <li>只有在开发环境下且存在错误时才显示错误球</li>
            </ul>
          </template>
        </el-alert>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch, onMounted, nextTick } from 'vue';
  import { ElMessage } from 'element-plus';
  import { Warning, List, Delete, Monitor, Cpu } from '@element-plus/icons-vue';
  import { globalErrorHandler, type ErrorInfo, networkErrorHandler } from '@/utils/errorHandler';
  import { debugErrorHandler } from '@/utils/debugErrorHandler';

  // 响应式数据

  const showQueue = ref(false);
  const errorQueue = ref<ErrorInfo[]>([]);
  const testData = ref('正常数据');

  // 监听错误队列变化
  const updateErrorQueue = () => {
    errorQueue.value = globalErrorHandler.getErrorQueue();
  };

  // 格式化时间
  const formatTime = (timestamp: number) => {
    return new Date(timestamp).toLocaleString('zh-CN');
  };

  // JavaScript 错误测试
  const triggerJSError = () => {
    throw new Error('这是一个手动触发的 JavaScript 错误 - 测试用');
  };

  const triggerTypeError = () => {
    // @ts-ignore
    const obj = null;
    obj.property.nested = '这会导致类型错误';
  };

  const triggerReferenceError = () => {
    // @ts-ignore
    console.log(undefinedVariable);
  };

  // Vue 组件错误测试
  const triggerRenderError = () => {
    // 通过改变数据导致渲染错误
    testData.value = {
      toString: () => {
        throw new Error('渲染时发生错误');
      },
    } as any;
  };

  const triggerLifecycleError = () => {
    nextTick(() => {
      throw new Error('生命周期钩子中的错误');
    });
  };

  const triggerWatchError = () => {
    const stopWatch = watch(
      () => testData.value,
      () => {
        throw new Error('Watch 回调中的错误');
      },
    );

    testData.value = '触发 watch 错误';

    // 立即停止监听以避免持续错误
    setTimeout(() => {
      stopWatch();
      testData.value = '正常数据';
    }, 100);
  };

  // Promise 错误测试
  const triggerPromiseError = () => {
    Promise.reject(new Error('未处理的 Promise 拒绝错误'));
  };

  const triggerAsyncError = async () => {
    await new Promise((_, reject) => {
      setTimeout(() => reject(new Error('Async/Await 中的错误')), 100);
    });
  };

  // 网络错误测试
  const triggerNetworkError = () => {
    networkErrorHandler(new Error('模拟的网络请求失败'), '/api/test-endpoint', 'GET');
  };

  const triggerResourceError = () => {
    // 创建一个不存在的图片元素来触发资源加载错误
    const img = new Image();
    img.src = '/non-existent-image.jpg?test=' + Date.now();
    document.body.appendChild(img);

    // 清理
    setTimeout(() => {
      if (img.parentNode) {
        img.parentNode.removeChild(img);
      }
    }, 1000);
  };

  // 错误管理功能
  const showErrorQueue = () => {
    showQueue.value = !showQueue.value;
    updateErrorQueue();
  };

  const clearErrors = () => {
    globalErrorHandler.clearErrorQueue();
    updateErrorQueue();
    ElMessage.success('错误队列已清空');
  };

  // 检查错误处理器健康状态
  const checkHandlerHealth = () => {
    debugErrorHandler.checkHealth();
    ElMessage.success('已检查错误处理器状态，请查看控制台');
  };

  // 测试错误球响应性
  const testErrorBall = () => {
    debugErrorHandler.triggerTestError('simple');
    ElMessage.info('已触发测试错误，检查错误球是否响应');
  };

  // 模拟错误处理器异常
  const simulateErrorHandlerFailure = () => {
    // 触发一个可能导致错误处理器异常的情况
    debugErrorHandler.triggerTestError('complex');
    ElMessage.warning('已模拟复杂错误，观察错误处理器行为');
  };

  // 定期更新错误队列
  onMounted(() => {
    const interval = setInterval(updateErrorQueue, 1000);

    // 组件卸载时清理定时器
    return () => clearInterval(interval);
  });
</script>

<style lang="scss" scoped>
  .error-test-page {
    min-height: calc(100vh - 160px);
    padding: 20px 0;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  }

  .error-test-card {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    border-radius: 12px;
    overflow: hidden;

    :deep(.el-card__header) {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      text-align: center;

      h2 {
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
      }

      .subtitle {
        margin: 0;
        opacity: 0.9;
        font-size: 14px;
      }
    }
  }

  .test-sections {
    display: grid;
    gap: 24px;
  }

  .test-section {
    padding: 20px;
    background: #f8f9ff;
    border-radius: 8px;
    border-left: 4px solid #667eea;

    h3 {
      margin: 0 0 16px 0;
      color: #2c3e50;
      font-size: 18px;
      font-weight: 600;
    }
  }

  .button-group {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;

    .el-button {
      display: flex;
      align-items: center;
      gap: 8px;
      min-width: 160px;
      justify-content: center;
    }
  }

  .error-queue {
    margin-top: 24px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;

    .empty-queue {
      text-align: center;
      color: #909399;
      padding: 20px;
    }
  }

  .error-item {
    padding: 12px;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .error-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;

      .error-type {
        background: #e74c3c;
        color: white;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: 600;
      }

      .error-time {
        font-size: 12px;
        color: #909399;
      }
    }

    .error-message {
      color: #e74c3c;
      font-weight: 500;
      margin-bottom: 8px;
    }

    .error-stack {
      pre {
        background: #f5f5f5;
        padding: 8px;
        border-radius: 4px;
        font-size: 11px;
        margin: 0;
        overflow-x: auto;
      }
    }
  }

  .usage-info {
    margin-top: 24px;

    ul {
      margin: 0;
      padding-left: 20px;

      li {
        margin-bottom: 8px;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    .button-group {
      .el-button {
        min-width: 140px;
        font-size: 14px;
      }
    }

    .test-section {
      padding: 16px;

      h3 {
        font-size: 16px;
      }
    }

    .error-test-card :deep(.el-card__header) {
      h2 {
        font-size: 20px;
      }

      .subtitle {
        font-size: 13px;
      }
    }
  }
</style>
